
// 购物车小球滚动效果
export const controllPath = (addBtn, shopCar, tag =  { color: '#4F78FF', time: 1, zIndex: 99999 })=> {
    let addBtnDom = null, shopCarDom = null;
    if(typeof addBtn === "string"){
        addBtnDom = document.querySelector(addBtn);
    } else if(addBtn instanceof HTMLElement){
        addBtnDom = addBtn
    } else {
        console.error("传入的参数错误： 第一个参数应为增加按钮的dom元素或该元素的选择器。");
        return;
    }

    if(typeof shopCar === "string"){
        shopCarDom = document.querySelector(shopCar);
    } else if(shopCar instanceof HTMLElement){
        shopCarDom = shopCar;
    }else {
        console.error("传入的参数错误： 第二个参数应为购物车的dom元素或该元素的选择器。");
        return;
    }

    // 获取两个dom的位置
    let addBtnposition = addBtnDom.getBoundingClientRect();
    let shopCarPosition = shopCarDom.getBoundingClientRect();
    let addBtnCenterX = (addBtnposition.left + addBtnposition.right) / 2;
    let addBtnCenterY = (addBtnposition.top + addBtnposition.bottom) / 2;
    let shopCarCenterX = (shopCarPosition.left + shopCarPosition.right) / 2;
    let shopCarCenterY = (shopCarPosition.top + shopCarPosition.bottom) / 2;
    //计算增加按钮 是在 相对于购物车的 左边还是右边（用于控制后面的移动方向）
    let relativePosition = addBtnCenterX > shopCarCenterX ? -1 : 1;
    // 获取连个dom之间的距离
    let xDistance = Math.abs(addBtnCenterX - shopCarCenterX);
    let yDistance = Math.abs(addBtnCenterY - shopCarCenterY);
    // 绘制小球并设置其位置
    let ballDom = drawBall(tag);
    ballDom.style.top = addBtnCenterY + "px";
    ballDom.style.left = addBtnCenterX + "px";
    document.body.appendChild(ballDom);

    /*
     * 根据一元二次方程的轨迹求出对象的系数 y = ax^2 + bx + c
     *  let coefficientC = 0;
     *  let coefficientB = 0;
     *  let coefficientA = yDistance / Math.pow(xDistance, 2);
     */
    //小球的横竖坐标
    let xAbscissa = 0, yAbscissa = 0;

    //设置移动路径
    let ballTimer = setInterval(function () {
        //每次重新坐标
        xAbscissa += 5 * relativePosition;
        yAbscissa = (yDistance / Math.pow(xDistance, 2)) * Math.pow(xAbscissa, 2);
        ballDom.style.top = addBtnCenterY + yAbscissa + "px";
        ballDom.style.left = addBtnCenterX + xAbscissa + "px";
        //检查是否到达终点
        let surplusDistance = parseInt(ballDom.style.left) - shopCarCenterX;

        if (Math.abs(surplusDistance) <= 10) {
            clearInterval(ballTimer);
            let element = document.getElementById("ballDom");
            if (element) element.parentNode.removeChild(element)
        }
    }, tag.time);
};



const drawBall = (tag) => {
    let ballDom = document.createElement("div");
    ballDom.style.width = "20px";
    ballDom.style.height = "20px";
    ballDom.style.border = "1px solid #4F78FF";
    ballDom.style.background = tag.color || '#4F78FF';
    ballDom.style.borderRadius = "50%";
    ballDom.style.position = "absolute";
    ballDom.style.zIndex = tag.zIndex || 99999;
    ballDom.id = 'ballDom'
    return ballDom;
}
